
var LODOP; //声明为全局变量 
var CNPrint;//菜鸟打印控件
var expressRex="";//运单号正则表达式
var packformName="";
var printName="";//打印机名称
var status="";
var printIDENTITY={AppKey:"23201703",Seller_ID:"1730045025"};
//菜鸟面单字段和实体映射
var cnFields = {
        "ali_waybill_short_address":"shortAddress",//大头笔
        "ali_waybill_package_center_name":"packageCenterName",//集散地名称
        "ali_waybill_package_center_code":"packageCenterCode",//集散地编码
        "ali_waybill_send_name":"warehouseContact",//"",//寄件人
        "ali_waybill_send_phone":"warehouseMobile",//"",//寄件人电话
        "ali_waybill_shipping_address":"warehouseAddress",//"",//寄件人地址
        "ali_waybill_consignee_name":"toName",//收件人
        "ali_waybill_consignee_phone":"toPhone",//收件人电话
        "ali_waybill_consignee_address":"toAddress",//收件人地址
        "ali_waybill_waybill_code":"expressNo",//面单号
        "ali_waybill_shipping_branch_code":"shippingBranchCode",//发件网点代码
        "ali_waybill_shipping_branch_name":"shippingBranchName",//发件网点名称
        "ali_waybill_ext_send_date":"printTime",//发件时间
        "ali_waybill_ext_sf_biz_type":"extSFBizType",//业务类型
        "ali_waybill_shipping_address_city":"fromCity",//发件地址
        ///自定义字段///
        "taskName":"taskName",//订单任务名称
        "origin":"origin",//原寄地
        "fromProvince":"fromProvince",//寄件人省
        "fromCity":"fromCity",//寄件人市
        "fromCounty":"fromCounty",//寄件人县
        "fromTowns":"fromTowns",//寄件人镇
        "fromAddress":"fromAddress",//详细地址
        "fromName":"fromName",//寄件人姓名
        "fromPhone":"fromPhone",//寄件人固定电话
        "fromMobile":"fromMobile",//寄件人手机
        "fromCompany":"fromCompany",//寄件人单位名称
        "fromZipcode":"fromZipcode",//邮政编码
        "toProvince":"toProvince",//收件人省
        "toCity":"toCity",//收件人市
        "toCounty":"toCounty",//收件人县
        "toTowns":"toTowns",//收件人镇
        "toAddress":"toAddress",//收件人详细地址
        "toCompany":"toCompany",//收货人单位名称
        "toName":"toName",//收件人姓名
        "bunick":"bunick",//收件人昵称
        "toPhone":"toPhone",//收件人固定电话
        "toMobile":"toMobile",//收件人手机号码
        "toZipcode":"toZipcode",//邮政编码
        "destination":"destination",//目的地
        "allCost":"allCost",//商品总价
        "number":"number",//商品数量
        "price":"price",//商品价格
        "productName":"productName",//商品名称
        "weight":"weight",//商品重量
        "ordeno":"ordeno",//订单号
        "waybillNo":"waybillNo",//运单号
        "stockInfo":"stockInfo",//库位
        "shopName":"shopName",//店铺名称
        "totalSkuNumber":"totalSkuNumber",//商品总数
        "printData":"printData",//打印详细时间
        "customSkuName":"customSkuName",//商家自定义商品名称
};  
function changeStatus(item){
	$("#firstExpressNumber").val('');
	status=item;
	if("packForm"==item){
		 packFormPrinter("packFormStylePrint");
	}else if("express"==item){
		 packFormPrinter("expressPrint");
	}else if("ebill"==item){
		 packFormPrinter("ebillPrint");
	}
}

function printExpress(taskName,printerName,content,width,height,rankno,expressNo) {
	LODOP.PRINT_INIT(taskName);
	LODOP.SET_PRINT_PAGESIZE(1,width,height,""); 
	LODOP.ADD_PRINT_TEXT(20,20,300,20,rankno);
	LODOP.ADD_PRINT_BARCODE(10, 200, 180, 40, "128B", expressNo);
	eval(content);
	if (LODOP.SET_PRINTER_INDEXA(printerName)) {
		LODOP.PRINT();
	}
}

function verify(content) {
	var result =content.match(expressRex);
	if(result==null){
	  return false;
	}
	return true;
}


function initLodop() {
	LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
}

function initCNPrint() {
	CNPrint = getCaiNiaoPrint(document.getElementById('CaiNiaoPrint_OB'), document.getElementById('CaiNiaoPrint_EM'));
	CNPrint.SET_PRINT_IDENTITY("AppKey="+printIDENTITY.AppKey+"&Seller_ID="+printIDENTITY.Seller_ID);
}
function initCNDesign() {
	CaiNiaoDesign = getCaiNiaoPrint(document.getElementById('CaiNiaoPrint_OB2'), document.getElementById('CaiNiaoPrint_EM2'));
	CaiNiaoDesign.SET_PRINT_IDENTITY("AppKey="+printIDENTITY.AppKey+"&Seller_ID="+printIDENTITY.Seller_ID);
}

function Moditify(item) {
	if (item.is(":checked")) {
		//CaiNiaoDesign.ADD_PRINT_TEXTA(item.attr("name"), 56, 32, 175, 30, item.val());
		//换成html标签 以支持html样式的文本
		CaiNiaoDesign.ADD_PRINT_HTM(0, 32, 175, 30,item.val());
		CaiNiaoDesign.SET_PRINT_STYLEA(0,"ItemName",item.attr("name"));
		defineParam.push(item.attr("name"));
	} else {
		CaiNiaoDesign.SET_PRINT_STYLEA(item.attr("name"), 'Deleted', !item.is(":checked"));
		defineParam=$.grep(defineParam, function(n,i){
		  return n != item.attr("name");
		});
	}
}

function CNDisplayDesign(cpCode,config){
	CaiNiaoDesign.PRINT_INITA(0,0,400,800,"菜鸟电子面单");
	CaiNiaoDesign.SET_SHOW_MODE("DESIGN_IN_BROWSE",true);
	CaiNiaoDesign.SET_PRINT_MODE("CAINIAOPRINT_MODE","CP_CODE="+cpCode+"&CONFIG=0");
	if(config){
		CaiNiaoDesign.ADD_PRINT_DATA("ProgramData",config);
	}
	CaiNiaoDesign.PRINT_DESIGN();
}

function getCaiNiaoDesignContent() {
	return CaiNiaoDesign.GET_VALUE("CustomProgramData", 0).replace(/\r\n|\n|\r/g,"");
}

function getBodyContentString(content) {
	content = content.replace(/<[^>]*?>(.*?)/gi, '='); //删除左部
	content = content.replace(/(.*?)<\/[^>]*?>/gi, '='); //删除右部
	var bodyContents = content.split("=");
	return bodyContents;
}


//整除
function Div(exp1, exp2){
	var n1 = Math.round(exp1); //四舍五入
	var n2 = Math.round(exp2); //四舍五入
	var rslt = n1 / n2; //除
	if (rslt >= 0){
	    rslt = Math.floor(rslt); //返回值为小于等于其数值参数的最大整数值。
	}else {
	    rslt = Math.ceil(rslt); //返回值为大于等于其数字参数的最小整数。
	}
	return rslt;
}

function ajaxPrintPackFormOrdenos(ordenos,packformStyleId){
showBg();
$.ajax({
		type : 'post',
		url : path+'/print/ajaxPrintPackFormOrdenos',
		data : 'ordenos=' + ordenos+'&packformStyleId='+packformStyleId,
		dataType : 'json',
		success : function(data) {
			 if (data.status == "1") {
				initLodop();
				$.each(data.content, function(i) {
					 printStyle(packformName,data.content[i].taskName,printName,data.content[i].content,data.content[i].ordeno,data.content[i].expressNo,data.content[i].taskName);
				});
			    $("#message").html("<span class=\"label label-success\">打印机加载完毕</span>");
			      closeBg();
			} else if (data.status == "-3") {
		    	closeBg();
				alert("请输入正确的运单号！");
			} else if (data.status == "0") {
			    closeBg();
				alert("加载错误！");
			}

		},

		error : function() {
            alert("服务器异常");
		}
	});
}
function ajaxPrintEBillExpress(ordenos,expressId,taskCode){
	  showBg();
	$.ajax({
			type : 'post',
			url : path+'/print/ajaxPrintEBillExpress',
			data : 'ordenos=' + ordenos+'&expressId='+expressId+'&taskCode='+taskCode,
			dataType : 'json',
			success : function(data) {
				 if (data.status == "1") {
					//initLodop();
					if(data.openCaiNiao == "1"){
						//初始化菜鸟控件
						//initCNPrint();
					}
					$.each(data.content, function(i) {
						    var str=data.content[i].content;
						    str=str.replace(/\r\n/g,"");
						    if(data.openCaiNiao == "1"){
						    	printMailExpressByCaiNiao(printName,data.width,data.height,data.content[i]);
						    }else if("YUNDA"==data.expressStyle.logisticsCompany.companyCode){
						    	printYunDa(data.content[i].content,printName);
						    }else{
						    	printMailExpress(data.content[i].taskName,printName,str,data.width,data.height,data.content[i].expressNo,data.expressStyle,data.content[i].ordeno);
						    }
					});
				    $("#message").html("<span class=\"label label-success\">打印机加载完毕</span>");
				       closeBg();
				} else if (data.status == "-3") {
			    	closeBg();
			    	jAlert("请输入正确的运单号！");
				} else if (data.status == "0") {
				    closeBg();
					jAlert(data.content);
				}

			},

			error : function() {

			}
		});
	}

//通过菜鸟打印电子面单
function printMailExpressByCaiNiao(printName,width,height,printerStyleType){
    console.info(printerStyleType);
    request  = {
        cmd : "print",
        requetID : printerStyleType.ordeno,
        version : "1.0",
        task : {
            taskID : printerStyleType.ordeno + Date.parse(new Date()),
            preview : false,
            printer : $("#expressPrint").val(),
            documents : [
                {
                    documentID : printerStyleType.ordeno,
                    contents : [
                        //电子面单部分
                        {
                            "encryptedData": printerStyleType.cnPrinterModel.printConfig.encryptedData,
                            "templateURL" : printerStyleType.cnPrinterModel.printConfig.templateURL,
                            "signature" : printerStyleType.cnPrinterModel.printConfig.signature,
                            "ver":printerStyleType.cnPrinterModel.printConfig.ver,
                            "data": {
                                "recipient": {
                                    "address": {
                                        "city": printerStyleType.cnPrinterModel.toCity,
                                        "detail": printerStyleType.cnPrinterModel.addres,
                                        "district": printerStyleType.cnPrinterModel.toCounty,
                                        "province": printerStyleType.cnPrinterModel.toProvince,
                                        "town": printerStyleType.cnPrinterModel.toTowns,
                                    },
                                    "name": printerStyleType.cnPrinterModel.toName,
                                    "phone": printerStyleType.cnPrinterModel.toPhone,
                                },

                                "sender": {
                                    "address": {
                                        "city": printerStyleType.cnPrinterModel.fromCity,
                                        "detail": printerStyleType.cnPrinterModel.fromAddress,
                                        "district": printerStyleType.cnPrinterModel.fromCounty,
                                        "province": printerStyleType.cnPrinterModel.fromProvince,
                                    },
                                    "mobile": printerStyleType.cnPrinterModel.fromMobile,
									"phone": printerStyleType.cnPrinterModel.fromPhone,
                                    "name": printerStyleType.cnPrinterModel.fromName
                                },
                                "shippingOption": {
                                    "code": "STANDARD_EXPRESS",
                                    "title": "标准快递"
                                },
                                "title": printerStyleType.cnPrinterModel.titleName
                            },
                            "waybillCode": printerStyleType.expressNo
                        },
                        //自定义区部分
                        {
                            templateURL : "http://cloudprint.cainiao.com/template/standard/341690/6",
                            data : {
                                "taskName": printerStyleType.taskName,
                                "customSkuName": printerStyleType.cnPrinterModel.customSkuName
                            }
                        }
                    ]
                }
            ]
        }
    };

    websocket.send(JSON.stringify(request));

}
function printMailExpress(taskName,printName,content,width,height,expressNo,expressStyle,orderno){
	
    var adjustTop = 0;
 	var adjustLeft = 0;
	LODOP.PRINT_INIT(taskName);
	//LODOP.ADD_PRINT_TEXT(10, 10, 200, 20, rankno);
	LODOP.SET_PRINT_PAGESIZE(1,width,height,""); 
	var strCenterStyle = "<style/>table {width:100%}</style>";
	LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", strCenterStyle + content);
	//LODOP.ADD_PRINT_BARCODE(27,43,220,40,"",expressNo);
	var companyCode = expressStyle.logisticsCompany.companyCode;
	if("YTO" == companyCode){
		LODOP.ADD_PRINT_BARCODE((38+adjustTop)+"mm", (11+adjustLeft)+"mm", "80mm", "12mm", "128C", expressNo);
		LODOP.ADD_PRINT_BARCODE((110+adjustTop)+"mm", (52+adjustLeft)+"mm", "45mm", "12mm", "128C", expressNo);			
	}
	else if("YUNDA" == companyCode){
		LODOP.ADD_PRINT_BARCODE((30+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((144+adjustTop)+"mm", (52+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);			
	}
	else if("QRT" == companyCode){
		LODOP.ADD_PRINT_BARCODE((5+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((113+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);			
	}else if("SF" == companyCode){
		LODOP.ADD_PRINT_BARCODE((15+adjustTop)+"mm", (7+adjustLeft)+"mm", "58mm", "15mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((93+adjustTop)+"mm", (50+adjustLeft)+"mm", "48mm", "13mm", "128Auto", expressNo);
	}else if("UC" == companyCode){
		LODOP.ADD_PRINT_BARCODE((90+adjustTop)+"mm", (12+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((140+adjustTop)+"mm", (16+adjustLeft)+"mm", "30mm", "10mm", "128Auto", expressNo);
	}else if("BJRFD-001" == companyCode){
		LODOP.ADD_PRINT_BARCODE((12+adjustTop)+"mm", (35+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((90+adjustTop)+"mm", (35+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
	}else if("DEPPON" == companyCode){
		LODOP.ADD_PRINT_BARCODE((58+adjustTop)+"mm", (20+adjustLeft)+"mm", "45mm", "11mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((99+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "11mm", "128Auto", expressNo);
	}else if("ZYKJ" == companyCode){
		LODOP.ADD_PRINT_BARCODE((12+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((100+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "11mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_IMAGE((12+adjustTop)+"mm", (12+adjustLeft)+"mm", "45mm", "13mm", "<img src='http://wms.paiu.com.cn/wms/static/images/zengyilogo.jpg' />");
		LODOP.ADD_PRINT_IMAGE((100+adjustTop)+"mm", (12+adjustLeft)+"mm", "45mm", "11mm", "<img src='http://wms.paiu.com.cn/wms/static/images/zengyilogo.jpg' />");
	}else if("EMS" == companyCode){
		LODOP.ADD_PRINT_BARCODE((10+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((73+adjustTop)+"mm", (15+adjustLeft)+"mm", "24mm", "7mm", "128Auto", orderno);
		LODOP.ADD_PRINT_BARCODE((98+adjustTop)+"mm", (7+adjustLeft)+"mm", "45mm", "13mm", "128Auto", expressNo);
	}else if("ZTO" == companyCode){
		 LODOP.ADD_PRINT_BARCODE((73+adjustTop)+"mm", (17+adjustLeft)+"mm", "80mm", "15mm", "128Auto", expressNo);
		 LODOP.ADD_PRINT_BARCODE((115+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "11mm", "128Auto", expressNo);
	}else if("STO" == companyCode){
		LODOP.ADD_PRINT_BARCODE((77+adjustTop)+"mm", (17+adjustLeft)+"mm", "80mm", "15mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((116+adjustTop)+"mm", (50+adjustLeft)+"mm", "50mm", "11mm", "128Auto", expressNo);
	}else if("QFKD" == companyCode){
		LODOP.ADD_PRINT_BARCODE((38+adjustTop)+"mm", (30+adjustLeft)+"mm", "45mm", "13mm", "128C", expressNo);
		LODOP.ADD_PRINT_BARCODE((108+adjustTop)+"mm", (52+adjustLeft)+"mm", "45mm", "12mm", "128C", expressNo);			
	}else if("HTKY" == companyCode){
		LODOP.ADD_PRINT_BARCODE((1+adjustTop)+"mm", (55+adjustLeft)+"mm", "45mm", "13mm", "128C", expressNo);
		LODOP.ADD_PRINT_BARCODE((90+adjustTop)+"mm", (10+adjustLeft)+"mm", "45mm", "12mm", "128C", expressNo);	
		LODOP.ADD_PRINT_BARCODE((62+adjustTop)+"mm", (1+adjustLeft)+"mm", "20mm", "20mm","QRCode",expressNo);	
		LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",1);			
	}else if("TTKDEX" == companyCode){
	    LODOP.ADD_PRINT_BARCODE((73+adjustTop)+"mm", (17+adjustLeft)+"mm", "80mm", "15mm", "128Auto", expressNo);
		LODOP.ADD_PRINT_BARCODE((115+adjustTop)+"mm", (50+adjustLeft)+"mm", "45mm", "11mm", "128Auto", expressNo);
	}else if("JD" == companyCode){
	    LODOP.ADD_PRINT_BARCODE((5+adjustTop)+"mm", (45+adjustLeft)+"mm", "56mm", "16mm", "Code39", expressNo);
		LODOP.ADD_PRINT_BARCODE((64+adjustTop)+"mm", (36+adjustLeft)+"mm", "61mm", "13mm", "Code39", expressNo);
	}
	//LODOP.SET_SHOW_MODE("BKIMG_PRINT", 1);
	//LODOP.PREVIEW();
	if (LODOP.SET_PRINTER_INDEXA(printName)) {
		LODOP.PRINT();
	}
}

function ajaxPrintPackExpressOrdenos(ordenos,firstExpress,expressId){
  showBg();
$.ajax({
		type : 'post',
		url : path+'/print/ajaxPrintPackExpressOrdenos',
		data : 'ordenos=' + ordenos+'&firstExpress='+firstExpress+'&expressId='+expressId,
		dataType : 'json',
		success : function(data) {
			 if (data.status == "1") {
				initLodop();
				$.each(data.content, function(i) {
					
					    var str=data.content[i].content;
					    str=str.replace(/\r\n/g,"");
					printExpress(data.content[i].taskName,printName,str,data.width,data.height,data.content[i].taskName,data.content[i].expressNo);
					
				});
			    $("#message").html("<span class=\"label label-success\">打印机加载完毕</span>");
			       closeBg();
			} else if (data.status == "-3") {
		    	closeBg();
				alert("请输入正确的运单号！");
			} else if (data.status == "0") {
			    closeBg();
				alert("加载错误！");
			}

		},

		error : function() {

		}
	});
}

function printStyle(indentfy,taskName, printerName, printContent,ordeno, expressNo,rankno){
     printFivePackStyle(taskName,printerName,printContent,ordeno,expressNo,rankno);
}

function printFivePackStyle(taskName, printerName, printContent,ordeno, expressNo,rankno) {
	LODOP.PRINT_INIT(taskName);
	LODOP.ADD_PRINT_TEXT(20,20,300,10,rankno);
	var strCenterStyle = "<style/>table {width:100%}</style>";
	LODOP.ADD_PRINT_HTM(115, 0, "100%", "100%", strCenterStyle+ printContent);
    LODOP.ADD_PRINT_BARCODE(40, 250, 350, 40, "128B", ordeno);
    if(expressNo){
    	LODOP.ADD_PRINT_BARCODE(500, 280, 200, 20, "128B", expressNo);
    }
	if (LODOP.SET_PRINTER_INDEXA(printerName)) {
		LODOP.PRINT();
	}
}

function getAjaxExpress() {
    var expressStylesId = $("#expressStylesId").val();
		$.ajax({
			type : 'post',
			url : path+'/v2/packformStyle/getAjaxExpress',
			data : 'expressStylesId=' + expressStylesId,
			dataType : 'json',
			success : function(data) {
				if (data.status == "1") {
					expressRex=data.content.logisticsCompany.regMailNo;
				}  else if (data.status == "0") {
					alert("获取运单号正则表达式错误！");
				}
			},

			error : function() {

			}
		});
	}
	
	function getAjaxPackformStyle() {
		var packformStylesId = $("#packformStylesId").val();
		if (packformStylesId == "" || packformStylesId == null) {
			alert("还没有这个随箱单");
			return;
		}
		$.ajax({
			type : 'post',
			url : path+'/v2/packformStyle/getAjaxPackformStyle',
			data : 'packformStylesId=' + $("#packformStylesId").val(),
			dataType : 'json',
			success : function(data) {
				if (data.status == "1") {

					packformName = data.name;
					//packStyleType = data.type;
				
				} else if (data.status == "0") {
					alert("获取随箱单信息错误！");
				}

			},
			error : function() {
				alert("服务器异常");
			}
		});
	}
	//韵达打印
	function printYunDa(value,printname){
		$.ajax({
			type : 'post',
			url : "http://127.0.0.1:9090/ydecx/service/mailpx/printDirect.pdf?t="+new Date().getTime(),
			data : 'tname=mailtmp_s8&docname=mailpdfm1&value='+value+'&printname='+printname,
			dataType : 'json',
			async: false//设置为同步,解决韵达打印不按顺序出纸的问题
		});
	}